package com.servlet.yanglaoyuan.service.impl;
import com.servlet.yanglaoyuan.pojo.EmergencyContact;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.servlet.yanglaoyuan.common.PageResult;
import com.servlet.yanglaoyuan.mapper.elderlyMapper;
import com.servlet.yanglaoyuan.pojo.Elderly;
import com.servlet.yanglaoyuan.pojo.ElderlyDTO;
import com.servlet.yanglaoyuan.service.elderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class elderServiceImpl implements elderService {
    @Autowired
    private elderlyMapper elderlyMapper;
    //增加
    @Override
    public void add(Elderly elderly) {
        elderlyMapper.add(elderly);
    }
    //修改
    @Override
    public void update(Integer id,Elderly elderly) {
        elderlyMapper.update(id,elderly);
    }
    //id查询
    @Override
    public Elderly getById(Integer id) {
        return elderlyMapper.getById(id);
    }
    //手机号查询
    @Override
    public Elderly getByPhone(String phone) {
        return elderlyMapper.getByPhone(phone);
    }
    //删除
    @Override
    public void delete(Integer id) {
        elderlyMapper.delete(id);
    }
    //分页查询
    @Override
    public PageResult<ElderlyDTO> findAll(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Elderly> list0 = elderlyMapper.findAll();
        List<ElderlyDTO> list = list0.stream().map(elderly -> new ElderlyDTO(elderly.getId(),elderly.getName(),elderly.getSex(),elderly.getAge(),elderly.getPhone(),elderly.getAddress(),elderly.getBloodType(),elderly.getHeight(),elderly.getWeight(),new EmergencyContact(elderly.getEmerName(),elderly.getEmerPhone(),elderly.getEmerRelation()))).toList();
        // 获取原始分页信息
        Page<Elderly> originalPage = (Page<Elderly>) list0;

        // 使用Page的静态方法创建分页对象
        Page<ElderlyDTO> dtoPage = new Page<>(originalPage.getPageNum(), originalPage.getPageSize());
        dtoPage.setTotal(originalPage.getTotal());
        dtoPage.addAll(list);

        return new PageResult<>(dtoPage.getTotal(), dtoPage.getResult());
    }

    //总数查询
    @Override
    public Long findTotal() {
        return elderlyMapper.findTotal();
    }

    @Override
    public List<Elderly> searchElderly(Map<String, String> params) {
        return elderlyMapper.searchElderly(params);
    }
}

